package cn.controller;

import cn.config.Result;
import cn.domain.User;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import cn.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
public class LoginController {
    @Autowired
    UserService userService;
    public static final String salt="1234";
    @RequestMapping("login")
    public Result login(@RequestBody User user, HttpServletRequest request){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
          wrapper.eq(User::getName,user.getName());
        User one = userService.getOne(wrapper);
        if (one==null){
            return  Result.fail("名字不存在");
        }
        if (!one.getPwd().equals(DigestUtil.md5Hex(user.getPwd()+salt))){
            return  Result.fail("密码不正确");
        }

        String token02 = JWT.create()
                .setPayload("uname", one.getName())
                .setPayload("roleName", one.getRoleName())
                .setSigner(JWTSignerUtil.none())
                .sign();

        JWT jwt = JWT.of(token02);
        String uname = jwt.getPayload("uname").toString();
        String roleName = jwt.getPayload("roleName").toString();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("token",token02);
        map.put("uname",uname);
        map.put("roleName",roleName);
        return Result.success(map);
    }
   @PostConstruct
    public  void  init(){
        String pwd="1234";
       String s = DigestUtil.md5Hex(pwd + salt);
                System.err.println(s);
    }
}
